<?php
declare (strict_types=1);

namespace app\course\service\live\admin;

use app\common\service\BaseService;
use app\course\logic\base\admin\Course as AdminCourse;
use app\course\logic\base\Course;
use app\course\logic\live\admin\LiveBoke;
use app\course\logic\live\admin\LiveSection as SectionLogic;
use app\course\logic\live\BokeKT;
use app\course\logic\live\BokeZB;
use app\course\model\live\CourseSectionLive as LiveData;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageForm;
use eduline\admin\page\PageList;
use think\annotation\Inject;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;

/**
 * 直播课程课时接口类-后台
 */
class LiveSection extends BaseService
{
    /**
     * @Inject()
     *
     * @var SectionLogic
     */
    protected $sectionLogic;

    /**
     * @Inject()
     *
     * @var LiveData
     */
    protected $liveData;

    /**
     * @Inject()
     * @var LiveBoke
     */
    protected $liveBoke;

    /**
     * @Inject()
     *
     * @var BokeZB
     */
    protected $bokeZB;

    /**
     * @Inject()
     *
     * @var BokeKT
     */
    protected $bokeKT;

    /**
     * @Inject()
     *
     * @var Course
     */
    protected $course;

    /**
     * 课时列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-28
     *
     * @param int $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function sectionTree(int $id)
    {
        $data = $this->sectionLogic->sectionTree($id);
        // 定义字段
        $keyList = [
            'title'       => ListItem::make()->title('名称')->width(200),
            'price'       => ListItem::make('custom')->title('价格(单位:元)'),
            'simple_time' => ListItem::make()->title('开课时间'),
            'live'        => ListItem::make('custom')->title('开课状态'),
        ];
        // 设置表单
        $list = app(PageList::class);
        // 表单字段
        $list->pageKey = $keyList;
        $list->datas   = $data;

        // 课程信息
        // 是否已经完结
        $list->is_finished = app(AdminCourse::class)->isFinished($id);

        return $list->send();
    }

    /**
     * 分类子集
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-28
     */
    public function getChildren(int $id, int $pid): Response
    {
        $data = $this->sectionLogic->sectionTree($id, $pid);

        return static::parseToData($data, 1, '获取成功');
    }

    /**
     * 创建课时
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-30
     */
    public function addSection(int $id = 0, int $pid = 0): Response
    {
        if (Request::isPost()) {
            $data = Request::post();
            $re   = $this->sectionLogic->addSection($id, $pid, $data);

            // return $this->parseToData($data, 1, 'test');
            return static::parseToData($re->toArray(), 1, '添加成功');
        }

        /* 创建课程界面配置 */
        $keyList = [
            'title' => FormItem::make()->title('课时名称')->required(),
        ];
        // 最后一个课时允许添加课件与价格
        if ($this->sectionLogic->isLastSction($id, $pid)) {
            $keyList['price']      = FormItem::make('inputNumber')->title('课时价格')->min(0)->precision(2);
            $keyList['time']       = FormItem::make('custom')->title('开课时间')->required();
            $keyList['class_hour'] = FormItem::make('inputNumber')->title('学时')->min(0);
            // $keyList['course_ids']            = FormItem::make('custom')->title('直播带课');
            $keyList['completion_conditions'] = FormItem::make('custom')->title('完成条件')->help('1. 累计学习时长达标后即学完课时<br />2. 0表示点击即完成');
        }
        // 设置表单
        $form = app(PageForm::class);
        // 表单字段
        $form->pageKey = $keyList;
        // 排序
        // $form->pageKeySort = ['mhm_id'];
        $form->saveMethod  = 'POST';
        $url               = '/course/admin/live/' . $id . '/section/' . $pid;
        $form->savePostUrl = $url;

        return $form->send();
    }

    /**
     * 修改课时界面
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-27
     *
     * @param int $sid [description]
     * @param int $id  [description]
     */
    public function update(int $id, int $sid): Response
    {
        if (Request::isPut()) {
            $data    = Request::put();
            $section = $this->sectionLogic->findOrFail($sid);
            $section = $this->sectionLogic->editSection($section, $data);

            return static::parseToData($section, 1, '编辑成功');
        }

        $data = $this->sectionLogic->where('id', $sid)->findOrFail();

        if ($data->course_ids) {
            $course_ids = explode(',', trim($data->course_ids, ','));
            foreach ($course_ids as &$course_id) {
                $course_id += 0;
            }
            unset($course_id);
            $data->course_ids = $course_ids;
        } else {
            $data->course_ids = [];
        }

        $data->course_ids = app(Course::class)->where('id', 'IN', $data->course_ids)->field('id,title,cover')->with(['cover_url'])->select();
        // 查询课时关联数据
        $live_data                = $this->liveData->where('room_no', $sid)->findOrEmpty();
        $data->playback_id_attach = $live_data;
        $data->playback_id        = $live_data->attach_id;

        $time         = time();
        $data->is_end = (int)($data->end_time < $time || (!$live_data->isEmpty() && $live_data->close_time < $time));
        $timeKeyList  = $data->is_end ? 'word' : 'custom';

        /* 创建课程界面配置 */
        $keyList = [
            'title' => FormItem::make()->title('课时名称')->required()->disabled(!!$data->is_end),
        ];
        if ($this->sectionLogic->isLastSction($id, $data->pid)) {
            $keyList['price'] = FormItem::make('inputNumber')->title('课时价格')->min(0)->precision(2)->disabled(!!$data->is_end);
            $keyList['time']  = FormItem::make($timeKeyList)->title('开课时间')->required();

            if ($data->start_time && $data->end_time) {
                if ($data->is_end) {
                    $data->time = date('Y-m-d H:i', $data->start_time) . ' - ' . date('Y-m-d H:i', $data->end_time);
                } else {
                    $data->time = [
                        'date'      => date('Y-m-d', $data->start_time),
                        'time_slot' => [
                            date('H:i', $data->start_time),
                            date('H:i', $data->end_time),
                        ],
                    ];
                }
            }

            $keyList['class_hour'] = FormItem::make('inputNumber')->title('学时')->min(0)->disabled(!!$data->is_end);
            // $keyList['course_ids']            = FormItem::make('custom')->title('直播带课');
            $keyList['completion_conditions'] = FormItem::make('custom')->title('完成条件')->help('1. 累计学习时长达标后即学完课时<br />2. 0表示点击即完成');
            if ($data->is_end && $data->live_provider !== 3) {
                // 只有课时 + 直播服务商不是CC事,才需要上传回放视频
                $keyList['playback_id'] = FormItem::make('custom')->title('直播回放视频');
            }
        }

        // 设置表单
        $form = app(PageForm::class);
        // 表单字段
        $form->pageKey     = $keyList;
        $form->saveMethod  = 'PUT';
        $url               = '/course/admin/live/' . $id . '/section/' . $sid;
        $form->savePostUrl = $url;

        $form->datas = $data;

        return $form->send();

    }

    /**
     * 编辑指定的字段
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-27
     */
    public function updateSort($sid): Response
    {
        $value = Request::put('best_sort/d');
        $video = $this->sectionLogic->updateSort($sid, $value);

        return static::parseToData($video, 1, '编辑成功');
    }

    /**
     * 删除课时
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-28
     *
     * @param int $sid [description]
     */
    public function delete(int $sid): Response
    {
        $this->sectionLogic->sectionDelete($sid);

        return static::parseToData([], 1, '删除成功');

    }

    /**
     * liveLink
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/03/20
     *
     * @param int $id
     * @param int $sid
     * @return Response
     */
    public function liveLink(int $id, int $sid): Response
    {
        $data = $this->liveData->findOrEmpty($sid);
        $link = '';
        if (!$data->isEmpty() && $roomid = $data->cc_room_id) {
            if ($data->live_type == 3) {
                $link = $this->bokeKT->getLoginLink($roomid);
            } else if ($data->live_type == 2) {
                $link = $this->bokeZB->getLoginLink($roomid);
            }
        } else if ($data->isEmpty()) {
            // 创建直播间
            $course = $this->course->findOrEmpty($id);
            if ($course->course_live_type == 1) {
                $roomid = $this->liveBoke->createZBRoom(['section_id' => $sid]);
                $link   = $this->bokeZB->getLoginLink($roomid);
            } else if ($course->course_live_type == 2) {
                $roomid = $this->liveBoke->createKtRoom(['section_id' => $sid]);
                $link   = $this->bokeKT->getLoginLink($roomid);
            }
        }
        $course = app(Course::class)->with(['teacher_name'])->findOrEmpty($id);

        return static::parseToData(['uri' => $link, 'teacher_name' => $course->teacher_name, 'course_title' => $course->title], 1, '');
    }

}
